package com.dsiab.manageService.controller;

import com.dsiab.manageService.common.CommonUtils;
import com.dsiab.manageService.common.ResponseMap;
import com.dsiab.manageService.entity.WebStatsDto;
import com.dsiab.manageService.service.ToolsService;
import com.dsiab.manageService.service.WebStatsService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/stats")
public class WebStatsController {

    @Autowired
    WebStatsService webStatsService;
    @Autowired
    CommonUtils commonUtils;
    @Autowired
    ToolsService toolsService;

    /**
     * 埋点
     * @param request
     * @param map
     * @return
     */
    @GetMapping("/getStats.gif")
    public ResponseMap getStats(HttpServletRequest request, @RequestParam Map map) {

        String ip = commonUtils.getIpAddr(request);
        log.info("ip:" + ip);
        String region = toolsService.getAddressFromIp(ip,false);
        WebStatsDto webStatsDto = new WebStatsDto();
        String type = (String) map.get("type");
        if (type == null){
            String userAgent = (String) map.get("userAgent");
            if (userAgent != null){
                webStatsDto.setUserAgent(userAgent);
                webStatsDto.setTitle((String) map.get("title"));
                webStatsDto.setDomain((String) map.get("domain"));
                webStatsDto.setReferrer((String) map.get("referrer"));
                webStatsDto.setScreen((String) map.get("screen"));
                webStatsDto.setLang((String) map.get("lang"));
                webStatsDto.setOs((String) map.get("os"));
                webStatsDto.setBrowse((String) map.get("browse"));
                webStatsDto.setDevice((String) map.get("device"));
                webStatsDto.setHref((String) map.get("hrefs"));
                webStatsDto.setIp(ip);
                webStatsDto.setRegion(region);
                webStatsDto.setVisitorId((String) map.get("visitorId"));
                webStatsService.insertWebStats(webStatsDto);
            }

        } else {
            webStatsDto.setVisitorId((String) map.get("visitorId"));
            webStatsDto.setLabel((String) map.get("label"));
            webStatsService.insertEvent(webStatsDto);
        }
        return ResponseMap.success();
    }

    /**
     * 查询统计
     * @return
     */
    @GetMapping("/getWebStatistics")
    @PreAuthorize("hasRole('ROLE_author')")
    public ResponseMap getWebStatistics(String type) {
        return ResponseMap.success( webStatsService.getWebStatistics(type));
    }
}
